package com.yhy.produce.controller;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.RandomUtil;
import cn.hutool.json.JSONUtil;
import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import com.google.common.collect.Lists;
import com.yhy.common.core.result.Result;
import com.yhy.common.excel.utils.EasyExcelUtil;
import com.yhy.produce.model.ExcelModel;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.util.List;

@Api(tags = "文件")
@Slf4j
@Controller
@RequestMapping("/file")
@RequiredArgsConstructor
public class FileController {

    @ApiOperation(value = "文件上传")
    @PostMapping(value = "/upload/excel", headers = "content-type=multipart/form-data")
    @ResponseBody
    public Result<?> uploadExcel(@RequestPart(value = "file") MultipartFile file) {
        List<ExcelModel> excelModels = Lists.newArrayList();
        EasyExcelUtil.importExcel(file, ExcelModel.class, new AnalysisEventListener<ExcelModel>() {

            @Override
            public void invoke(ExcelModel excelModel, AnalysisContext analysisContext) {
                // 解析数据. 为防止内存溢出，3000条保存一次
                log.debug("解析到第{}条数据: {}", excelModels.size() + 1, JSONUtil.toJsonStr(excelModel));
                excelModels.add(excelModel);
                if (excelModels.size() == 3000) {
                    log.info("invoke保存数据: {} 条", excelModels.size());
                    excelModels.clear();
                }
            }

            @Override
            public void doAfterAllAnalysed(AnalysisContext analysisContext) {
                log.debug("数据全部解析完成");
                if (CollUtil.isNotEmpty(excelModels)) {
                    log.info("doAfterAllAnalysed保存数据: {} 条", excelModels.size());
                }
            }
        });
        return Result.ok();
    }

    @ApiOperation(value = "文件下载")
    @GetMapping(value = "/export/excel")
    public void export(HttpServletResponse response) {
        List<ExcelModel> excelModels = Lists.newArrayList();
        for (int i = 2; i <= 10000; i++) {
            ExcelModel excelModel = new ExcelModel();
            excelModel.setId(i - 1);
            excelModel.setName(RandomUtil.randomString(10));
            excelModel.setAge((i / (i / 2)) - 1);
            excelModel.setAddress(RandomUtil.randomString(50));
            excelModels.add(excelModel);
        }
        EasyExcelUtil.exportExcel(response, excelModels, "用户", "用户list");
    }

}